import { ref, onMounted } from 'vue'

export default {
  setup() {
    const dinoStyle = ref({})
    const cactusStyle = ref({})
    const score = ref(0)
    let gameInterval = null

    const startGame = () => {
      gameInterval = setInterval(() => {
        // 更新游戏状态
        updateGameStatus()
      }, 100)
    }

    const updateGameStatus = () => {
      // 更新障碍物位置
      cactusStyle.value.left = parseInt(cactusStyle.value.left) - 5 + 'px'

      // 检查碰撞
      if (isCollision()) {
        alert('游戏结束')
        clearInterval(gameInterval)
      }

      // 更新得分
      if (parseInt(cactusStyle.value.left) < -39) {
        score.value++
        cactusStyle.value.left = '1000px'
      }
    }

    const isCollision = () => {
      const dinoRect = document.getElementById('dino').getBoundingClientRect()
      const cactusRect = document.getElementById('cactus').getBoundingClientRect()
      return (
        dinoRect.right >= cactusRect.left &&
        dinoRect.left <= cactusRect.right &&
        dinoRect.bottom >= cactusRect.top &&
        dinoRect.top <= cactusRect.bottom
      )
    }

    onMounted(() => {
      startGame()
      window.addEventListener('keydown', (e) => {
        if (e.code === 'Space') {
          // 小恐龙跳跃
          dinoStyle.value.bottom = '100px'
        }
      })
    })

    return {
      dinoStyle,
      cactusStyle,
      score
    }
  }
}